package handlers

import (
	"content-crafter/cache"
	"content-crafter/models"
	"content-crafter/pkg"
	"encoding/json"
	"github.com/gin-gonic/gin"
	"strconv"
	"time"
)

func Login(c *gin.Context) {
	username := c.PostForm("username")
	password := c.PostForm("password")
	if username == "" || password == "" {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "字段不能为空",
		})
		return
	}
	var user models.User
	err := models.DB.Where("username=?", username).First(&user).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "用户名不存在",
		})
		return
	}

	if pkg.Md5Str(password) != user.Password {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "密码错误",
		})
		return
	}

	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "登录成功",
	})
	return

}

func Add(c *gin.Context) {
	title := c.PostForm("title")
	content := c.PostForm("content")
	img := c.PostForm("img")
	book := models.Book{
		Title:   title,
		Content: content,
		Img:     img,
	}

	err := models.DB.Create(&book).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "添加失败",
		})
		return
	}
	redis_key := "book_add_" + strconv.Itoa(int(book.ID))
	var books models.Book
	models.DB.Where("id=?", book.ID).First(&books)
	jsonBook, _ := json.Marshal(books)
	cache.Rdb.Set(cache.Ctx, redis_key, jsonBook, time.Hour*2)
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "添加成功",
	})
	return
}

func Upload(c *gin.Context) {
	file, err := c.FormFile("img")
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "图片获取失败",
		})
		return
	}
	path := "static/img/" + file.Filename
	err = c.SaveUploadedFile(file, path)
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "上传失败",
		})
		return
	} else {
		url := "http://" + c.Request.Host + "/" + path
		c.JSON(200, gin.H{
			"code": 200,
			"msg":  "上传成功",
			"data": url,
		})
		return
	}

}

func Detail(c *gin.Context) {
	id := c.Query("id")
	var book models.Book
	err := models.DB.Where("id=?", id).First(&book).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "查询失败",
		})
		return
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "查询成功",
		"data": book,
	})
	return
}

func Del(c *gin.Context) {
	id := c.Query("id")
	models.DB.Where("id=?", id).Delete(&models.Book{})

	redis_key := "book_id_" + id
	cache.Rdb.Del(cache.Ctx, redis_key)
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "删除成功",
	})
	return

}

func List(c *gin.Context) {
	var book []models.Book
	redis_key := "book_list"
	cacheData, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	if cacheData == "" {
		models.DB.Find(&book)
		jsonData, _ := json.Marshal(book)
		cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(cacheData), &book)
	}

	c.JSON(200, gin.H{
		"code": 500,
		"msg":  "查询成功",
		"data": book,
	})
	return
}
